package cn.gs.util.set;

// @author gs
import com.sleepycat.collections.StoredSortedMap;
import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class BDBSet<T> implements Set<T> {

    Map<T, Boolean> map;

    public BDBSet(File dir, String name, Class<T> clazz) {
        map = BDBMap.createAndBindDatabase(dir.getAbsolutePath(), name, clazz, Boolean.class);
    }

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
        return map.containsKey(o);
    }

    @Override
    public Iterator<T> iterator() {
        return map.keySet().iterator();
    }

    @Override
    public T[] toArray() {
        return (T[]) toArray(new Object[map.size()]);
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return map.keySet().toArray(a);
    }

    @Override
    public boolean add(T e) {
        map.put(e, Boolean.TRUE);
        return true;
    }

    @Override
    public boolean remove(Object o) {
        boolean b = map.containsKey(o);
        map.remove(o);
        return b;
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        for (Object o : c) {
            if (!contains(o)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean addAll(Collection<? extends T> c) {
        for (T o : c) {
            add(o);
        }
        return true;
    }

    @Override
    public boolean retainAll(Collection c) {
        boolean modified = false;
        Iterator<T> it = iterator();
        while (it.hasNext()) {
            if (!c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        for (Object o : c) {
            remove(o);
        }
        return true;
    }

    @Override
    public void clear() {
        map.clear();
    }
}
